#!/usr/bin/env python
# -*- coding: UTF-8 -*-

class TRip:
	def __init__(self, org, dest, title=0):
		self.__org = org
		self.__dest = dest
		self.__title = title
		self.__name = ''
		# video
		self.__video = []
		# audio
		self.__audio =  []
		# subtitles
		self.__sub = []
		# contenedor 
		self.__contenedor = 'mkv'
		# capitulos
		self.__capitulos = 0 
		# capitulos a ripear
		self.__cmdChapsToRip = "0"
		print "objeto TRip inicializado", org, dest, title

	def setName(self, name):
		self.__name = name

	def addVideo(self, data, fin):
		self.__video += [(data, fin)]		

	def addAudio(self, id, data, fin):
		if id not in [x for (x,y,z) in self.__audio]:
			self.__audio += [(id, data, fin)]

	def addSub(self, id, data, fin):
		if id not in [x for (x,y,z) in self.__sub]:
			self.__sub += [(id, data, fin)]
	
	def setContenedor(self, type):
		self.__contenedor = type
	
	def setCapitulos (self):
		self.__capitulos = 1
		
	def setCapitulosToRip (self,primero = 0, ultimo = 0):
		
		self.__cmdChapsToRip = str(primero) + "-" + str(ultimo)

	def getCmdVideo(self):
		noes = "-noautosub -nocache -noslices -nosound"
		cores = "1"
		try:
			cores = re.search("cpu cores.*(\d+)",commands.getoutput('cat /proc/cpuinfo')).groups()[0]
		except:
			pass
		text = ''
		for (data, fin) in self.__video:
			print data.getDuracion()
			print fin
			bitrate = 900
			audios = 0
			for (x, y, audiofin) in self.__audio:
				if audiofin['codec'] in ['mp3', 'ogg stereo', 'aac stereo']:
					audios += int(data.getDuracion()) * 130
				elif audiofin['codec'] in ['ogg 5.1', 'aac 5.1']:
					audios += int(data.getDuracion()) * 350
				elif audiofin['codec'] in ['ac3']:
					audios += int(data.getDuracion()) * 480 
			
			print int(fin['tam']), int(fin['tam'])*1024*8
			print audios
			print int(fin['tam'])*1024*8 - audios
			print ( int(fin['tam'])*1024*8 - audios ) / int(data.getDuracion())
			bitrate = ( int(fin['tam'])*1024*8 - audios ) / int(data.getDuracion())
			print bitrate
			if bitrate < 750: bitrate = 750
			if bitrate > 1500: bitrate = 1500

			cropCmd = ",crop="+data.getCrop()
			if fin['entrelazado']:
				filtros = "pullup,softskip" + cropCmd + ",pp=ci,harddup"
			else: 
				filtros = "pullup,softskip" + cropCmd + ",harddup"
			if self.__org == '"/dev/dvd"' or fin['hayquevolcar']:
				org = " \"" + str(self.__dest)+"dvd-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".vob\""
			else:
				org =  " dvd://"+str(self.__title)+" -dvd-device " + self.__org

			if fin['codec'] == 'h264' :
				if fin['calidad'] == 'Optima':
				#ops = "subq=6:frameref=5:b_pyramid:weight_b:brdo:8x8dct:mixed_refs:me=umh:cabac:partitions=all:trellis=2:bframes=3:crf=21:threads="     + cores
					ops = "subq=6:frameref=5:b_pyramid:weight_b:brdo:8x8dct:mixed_refs:me=umh:cabac:partitions=all:trellis=2:bframes=3:direct_pred=auto:no_fast_pskip:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['calidad'] == 'Buena':
					ops = "subq=6:frameref=3:b_pyramid:weight_b:8x8dct:mixed_refs:me=umh:cabac:trellis=1:bframes=3:direct_pred=auto:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['calidad'] == 'Media':
					ops = "subq=4:frameref=1:b_pyramid:weight_b:me=hex:cabac:trellis=1:bframes=2:direct_pred=auto:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['calidad'] == 'Baja':
					ops = "subq=2:frameref=1:b_pyramid:weight_b:me=dia:cabac:trellis=1:bframes=1:direct_pred=auto:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['tipo'] <> "Dibujos" :
					ops += ":nodct_decimate"
				text += "mencoder " + noes + " "+org+" -vf " + filtros + " -oac copy -sws 7 -ovc x264 -x264encopts " + ops + ":turbo=1:pass=1" + " -o /dev/null\n"
				text += "mencoder " + noes + " "+org+" -vf " + filtros + " -oac copy -sws 7 -ovc x264 -x264encopts " + ops + ":pass=2" + " -o \"" + str(self.__dest) + "video-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".h264\"\n"
			elif fin['codec'] == 'xvid' :
				if fin['calidad'] == 'Optima':
					#ops = "autoaspect:par=vga11:vhq=4:bvhq=1:chroma_opt:quant_type=mpeg:noqpel:trellis:nogmc:max_bframes=2:fixed_quant=3:threads=" + cores
					ops = "autoaspect:par=vga11:vhq=4:bvhq=1:chroma_opt:quant_type=mpeg:noqpel:trellis:nogmc:max_bframes=2:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['calidad'] == 'Buena':
					ops = "autoaspect:par=vga11:vhq=2:bvhq=1:chroma_opt:quant_type=mpeg:noqpel:trellis:nogmc:max_bframes=2:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['calidad'] == 'Normal':
					ops = "autoaspect:par=vga11:vhq=0:bvhq=0:nochroma_opt:quant_type=h263:noqpel:trellis:nogmc:max_bframes=2:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['calidad'] == 'Baja':
					ops = "autoaspect:par=vga11:vhq=0:bvhq=0:nochroma_opt:quant_type=h263:noqpel:trellis:nogmc:max_bframes=2:threads=" + cores + ":bitrate=" + str(bitrate)
				if fin['tipo'] == "Dibujos" :
					ops += ":nogreyscale:cartoon"
				elif fin['tipo'] == "Blanco y Negro" :
					ops += ":nocartoon:greyscale"
				else:
					ops += ":nogreyscale:nocartoon"
				text += "mencoder " + noes + " "+org+" -vf " + filtros + " -oac copy -sws 7 -ovc xvid -xvidencopts " + ops + ":turbo:pass=1" + " -o /dev/null\n"
				text += "mencoder " + noes + " "+org+" -vf " + filtros + " -oac copy -sws 7 -ovc xvid -xvidencopts " + ops + ":pass=2" + " -o \"" + str(self.__dest) + "video-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".xvid\"\n"
		
			self.escribeEncode(text)
			return text
		
	def getCmdAudio(self):
		import re
		text = ''
		noes = "-noconsolecontrols -noautosub -nojoystick -nomouseinput -nolirc -nocache -noslices -noframedrop"
		for (id, data, fin) in self.__audio:
			fid 	= "audio-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+"_"+str(id)+"_"+str(fin['lang'])

			if self.__org == '"/dev/dvd"' or fin['hayquevolcar']:
				org = " \"" + str(self.__dest)+"dvd-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".vob\""
			else:
				org =  " dvd://"+str(self.__title)+" -dvd-device " + self.__org
				
			if fin['codec'] == "ac3":
				text += "mencoder -nocache -mc 0 -aid " + str(fin['aid']) + " -o \"" + str(self.__dest) + fid + ".ac3\" -ovc frameno -of rawaudio -oac copy " + org + "\n" 
			elif fin['codec'] == "ogg stereo":
				text += "mkfifo \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				text += "oggenc -r -R 44100 -q 3 -C 2 -o \"" + str(self.__dest) + fid + ".ogg\" \"" + str(self.__dest)+ "fifo-" + fid + "\"&"
				text += " mplayer " + noes + " -noframedrop -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.__dest)+ "fifo-" + fid + "\" -srate 44100 -af volnorm=1 -aid " + str(fin['aid']) + " " + org + "\n"
				text += "rm \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				
			elif fin['codec'] == "ogg 5.1":
				text += "mkfifo \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				text += "oggenc -r -R 44100 -q 3 -C 6 -o \"" + str(self.__dest) + fid + ".ogg\" \"" + str(self.__dest)+ "fifo-" + fid + "\"&"
				text += " mplayer " + noes + " -noframedrop -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.__dest)+ "fifo-" + fid + "\" -srate 44100 -af volnorm=1,lavcresample=44100 -channels 6 -aid " + str(fin['aid']) + " " + org + "\n"
				text += "rm \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				
			elif fin['codec'] == "mp3":
				text += "mkfifo \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				text += "lame --nohist -h -r -x -s 44,1 --preset fast medium \"" + str(self.__dest)+ "fifo-" + fid + "\" \"" + str(self.__dest) + fid + ".mp3\" &"
				text += " mplayer " + noes + " -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.__dest)+ "fifo-" + fid + "\" -srate 44100 -af volnorm=1,lavcresample=44100 -channels 2 -aid " + str(fin['aid']) + " " + org + "\n"
				text += "rm \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				
			elif fin['codec'] == "aac stereo":
				text += "mkfifo \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				text += "faac -P -q 100 -R 48000  -C 2 -X --mpeg-vers 4 -o \"" + str(self.__dest) + fid + ".aac\" \"" + str(self.__dest)+ "fifo-" + fid + "\" &"
				#text += "neroAacEnc -q 0.6 -ignorelength -if \"" + str(self.__dest)+ "fifo-" + fid + "\" -of \"" + str(self.__dest) + fid + ".aac\" &"
				text += " mplayer " + noes + " -mc 0 -vc null -vo null -ao pcm:file=\"" + str(self.__dest)+ "fifo-" + fid + "\" -af volnorm=1 -channels 2 -aid " + str(fin['aid']) + " " + org + "\n"
				text += "rm \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				
			elif fin['codec'] == "aac 5.1":
				text += "mkfifo \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
				text += "faac -P -q 100 -R 48000 -C 6 -X --mpeg-vers 4 -o \"" + str(self.__dest) + fid + ".aac\" \"" + str(self.__dest)+ "fifo-" + fid + "\" &"
				#text += "neroAacEnc -q 0.6 -ignorelength -if \"" + str(self.__dest)+ "fifo-" + fid + "\" -of \"" + str(self.__dest) + fid + ".aac\" &"
				text += " mplayer " + noes + " -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.__dest)+ "fifo-" + fid + "\" -af volnorm=1 -channels 6 -aid " + str(fin['aid']) + " " + org + "\n"
				text += "rm \"" + str(self.__dest)+ "fifo-" + fid + "\"\n"
			
		self.escribeEncode(text)
		return text

	def getCmdSub(self):
		import commands
		from re import search
		text = ''
		for (id, data, fin) in self.__sub:
			lang 	= data['idioma'] 
			fid 	= "sub-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+"_"+str(id)+"_"+str(fin['lang'])
			
			noes = "-noautosub -nocache -noslices -nosound "
			if self.__org == '"/dev/dvd"' or fin['hayquevolcar']:
				org = " \"" + str(self.__dest)+"dvd-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".vob\""
			else:
				org =  " dvd://"+str(self.__title)+" -dvd-device " + self.__org
				
			text += "mencoder " + noes + " " + org + " -of rawaudio -ovc copy -o /dev/null -vobsubout \"" + str(self.__dest) + fid + "\" -vobsuboutindex 0 -vobsuboutid " + lang + " -sid " + str(fin['sid']) + "\n"
			cmdPaleta = "mencoder dvd://"+str(self.__title)+" -dvd-device " + str(self.__org) + " -noautosub -nocache -nosound -of rawaudio -ovc copy -o /dev/null -vobsubout sub -vobsuboutindex 0 -vobsuboutid " + lang + " -sid " + str(fin['sid']) + " -frames 0 1> /dev/null 2> /dev/null"
			print cmdPaleta
			commands.getoutput(cmdPaleta)
			paleta = search("(palette:.*)",open ("sub.idx",'r').read()).groups()[0]
			commands.getoutput("rm sub.idx sub.sub")
			text += "echo \"" + paleta + "\" >> \"" + str(self.__dest) + fid + ".idx\"\n"
		self.escribeEncode(text)
		return text

	def getCmdDump(self):
		text = "mplayer -noconsolecontrols -noautosub -nojoystick -nomouseinput -nolirc -chapter " + self.__cmdChapsToRip + " dvd://"+str(self.__title)+" -dvd-device " + self.__org + " -dumpstream -dumpfile \"" + str(self.__dest) + "dvd-t" + str(self.__title)+ "-c_" +self.__cmdChapsToRip+".vob\"\n"
		if self.__org == '"/dev/dvd"':
			text += "eject " + self.__org
		self.escribeRipeado(text)
		return text + "\n"
		
	def getCmdMergeAll(self):
		if self.__contenedor == 'mkv':
			text = "mkvmerge --title \"" + self.__name + "\" -o \"" + str(self.__dest)+ "final-dvd-T" + str(self.__title) + "-c_" +self.__cmdChapsToRip+".mkv\""
		elif self.__contenedor == 'mp4':
			text = "MP4Box -new -brand mp42 -tmp \"" + str(self.__dest)+ "\" "

		for (data, fin) in self.__video:
			file = "\"" + str(self.__dest) + "video-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+"." + fin['codec'] + "\""
			if self.__contenedor == 'mkv':
				text += " -A -S -B --no-chapters --no-attachments --no-tags " + file
			elif self.__contenedor == 'mp4':
				if fin['codec'] == '264': 
					text += ' -add '+ file +':fmt=h264:fps=25.000#video'
				elif fin['codec'] == 'xvid': 
					text += ' -add '+ file +':fmt=mpeg4-video:fps=25.000#video'

		for (id, data, fin) in self.__audio:
			fid 	= "audio-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+"_"+str(id)+"_"+str(fin['lang'])
			file 	= "\"" + str(self.__dest) + fid + "." + fin['codec'].split(' ')[0]+ "\""
			if self.__contenedor == 'mkv':
				text += " -S -D -B --no-chapters --no-attachments --no-tags --language 0:" + fin['lang'] + " " + file
			elif self.__contenedor == 'mp4':
				text += ' -add '+ file +':fmt='+ fin['codec'].split(' ')[0] + ':lang=' + fin['lang'] + '#audio'
			
		for (id, data, fin) in self.__sub:
			fid  = "sub-t"+str(self.__title)+"-c_" +self.__cmdChapsToRip+"_"+str(id)+"_"+str(fin['lang'])
			file = "\"" + str(self.__dest) + fid + ".idx\""
			if self.__contenedor == 'mkv':
				text += " -A -D -B --no-chapters --no-attachments --no-tags " + file
			elif self.__contenedor == 'mp4':
				text += " -add "  + file + ':fmt=vobsub:lang='+ fin['lang']
		if self.__capitulos:
			import commands
			if self.__contenedor == 'mkv':
				commands.getoutput("dvdxchap -t " + str(self.__title) + " -c " + self.__cmdChapsToRip + " \"" + str(self.__org) + "\" > \"" + str(self.__dest)+"chapter-T"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".txt\"")
				text += " --chapter-language spa  --chapters \"" + str(self.__dest)+"chapter-T"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".txt\"\n"
			elif self.__contenedor == 'mp4':
				text += " -chap \"" + str(self.__dest)+"chapter-T"+str(self.__title)+"-c_" +self.__cmdChapsToRip+".txt\""
		if self.__contenedor == 'mp4':
			text += " \"" + str(self.__dest)+ "final-dvd-T" + str(self.__title) + "-c_" +self.__cmdChapsToRip+".mp4\"\n"
		else:
			text += "\n" 
		
		self.escribeEncode(text)
		return text
			
	def escribeEncode(self, data):
		f = open (self.__dest+"/encode.sh",'a')
		f.write(data)
		f.close()

	def escribeRipeado(self, data):
		datosRipAnterior = [""]
		try:
			f = open (self.__dest+"/rip.sh",'r')
			datosRipAnterior = f.readlines() 
			f.close()
		except:
			pass
		f = open (self.__dest+"/rip.sh",'w')
		f.truncate()
		if self.__org == '"/dev/dvd"' or fin['hayquevolcar']:
			print [datosRipAnterior]
			f.writelines(datosRipAnterior[:-1])
		else:
			f.writelines(datosRipAnterior)
		f.write(data)
		f.close()

